#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import numpy as np
import cv2
import os

#templates
path = os.path.join(os.path.dirname(__file__), 'template/t%s.png')
# print path
ts = [cv2.imread(path % (i,), 0) for i in range(10)]
os = [np.count_nonzero(t) for t in ts]


def recognize(f):
    img = cv2.imread(f)
    grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    binImg = cv2.threshold(grayImg, 127, 1, cv2.THRESH_BINARY_INV)[1]
    binImg = np.concatenate((binImg, np.ones([4,150], dtype=np.uint8)), axis=0)

    code = []
    for i in range(4):
        ds = [cv2.minMaxLoc(cv2.matchTemplate(binImg, t, cv2.TM_CCOEFF) / 2500) for (t,o) in zip(ts,os)]
        maxIdx = np.argmax([d[1] for d in ds])
        _, maxVal, _, maxLoc = ds[maxIdx]
        code.append((maxIdx, maxLoc))
        xLoc, yLoc = maxLoc
        w, h = ts[maxIdx].shape[::-1]
        tm = ts[maxIdx].copy()
        binImg[yLoc:yLoc+h, xLoc:xLoc+w] = np.logical_and(binImg[yLoc:yLoc+h, xLoc:xLoc+w], np.logical_not(tm))
    
    c = map(lambda t: str(t[0]), sorted(code, key=lambda x: x[1][0]))
    return "".join(c)


if __name__ == '__main__':
    print recognize('C:\Users\Desktop\\01.jpg')
